Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Serialization
Imports Toub.MediaCenter.Dvrms.Metadata

Public Class Form1

    Private DVRMS As DVRMSCheckedListBoxItem = Nothing
    Private bIsDirty As Boolean = False
    Private SaveFolder As String = Nothing
    Private WMTags() As MetadataItem
    Private RedoBuffer As New Queue(Of String)

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim fTags As String = System.AppDomain.CurrentDomain.BaseDirectory & "\" & "DVRMSTags.xml"
        If Not IO.File.Exists(fTags) Then
            IO.File.WriteAllText(fTags, My.Resources.DVRMSTags)
        End If
        Try
            Dim xmlDoc As XmlDocument = New XmlDocument()
            xmlDoc.Load(fTags)
            Dim xmlNode As XmlNode
            ReDim WMTags(xmlDoc.DocumentElement.ChildNodes.Count - 1)
            Dim ii As Integer = 0
            For Each xmlNode In xmlDoc.DocumentElement.ChildNodes
                If Not CType(xmlNode, XmlElement).HasAttribute("Name") Then Continue For
                If Not CType(xmlNode, XmlElement).HasAttribute("Type") Then Continue For

                Dim Name As String, Type As String, Value As String
                Dim oVal As Object, oType As MetadataItemType
                Name = CType(xmlNode, XmlElement).Attributes("Name").Value
                Type = CType(xmlNode, XmlElement).Attributes("Type").Value
                Value = CType(xmlNode, XmlElement).InnerText
                oType = [Enum].Parse(GetType(MetadataItemType), Type)
                Select Case oType
                    Case MetadataItemType.Binary : oVal = Encoding.ASCII.GetBytes(Value)
                    Case MetadataItemType.Boolean : oVal = CBool(Value)
                    Case MetadataItemType.Dword : oVal = Int32.Parse(Value)
                    Case MetadataItemType.Guid : oVal = Value
                    Case MetadataItemType.String : oVal = Value
                    Case MetadataItemType.Word : oVal = Int16.Parse(Value)
                    Case MetadataItemType.Qword : oVal = Int64.Parse(Value)
                    Case Else : Continue For
                End Select
                Dim item As New MetadataItem(Name, oVal, oType)
                WMTags(ii) = item : ii += 1
            Next
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        My.Settings.Save()
    End Sub

    Private Sub ToolStripItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles OpenToolStripMenuItem.Click, OpenToolStripButton.Click, _
            SaveToolStripMenuItem.Click, SaveToolStripButton.Click, _
            ExitToolStripMenuItem.Click, CustomizeToolStripMenuItem.Click
        Select Case True
            Case sender.Equals(OpenToolStripMenuItem), sender.Equals(OpenToolStripButton)
                LoadDVRMSFiles()
            Case sender.Equals(SaveToolStripMenuItem), sender.Equals(SaveToolStripButton)
                SaveFiles()
            Case sender.Equals(ExitToolStripMenuItem)
                Me.Close()
            Case sender.Equals(CustomizeToolStripMenuItem)
                XMLDVRMSFiles()
        End Select
    End Sub

    Private Sub XMLDVRMSFiles()
        If SaveFolder Is Nothing Then
            If SaveFiles() Is Nothing Then Return
        End If
        Me.ofdDVRMS.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        If Me.ofdDVRMS.ShowDialog <> Windows.Forms.DialogResult.OK Then Return
        Dim sfname() As String = Me.ofdDVRMS.FileNames
        For Each fname As String In sfname
            Using editor As New DvrmsMetadataEditor(fname)
                WriteXMLMetaData(editor.GetAttributes, IO.Path.GetFileNameWithoutExtension(fname))
            End Using
        Next
    End Sub

    Private Sub WriteXMLMetaData(ByVal meta As IDictionary, ByVal sf As String)
        Dim inWM As Boolean = False
        Dim settings As New XmlWriterSettings
        settings.Indent = True
        settings.OmitXmlDeclaration = True
        Using writer As XmlWriter = XmlWriter.Create(SaveFolder & "\" & sf & ".xml", settings)
            writer.WriteStartDocument(True)
            writer.WriteStartElement("dvrms")
            Dim xs As SortedList = New SortedList(meta)
            For Each name As String In xs.Keys
                Dim item As MetadataItem = meta(name)
                If item.Name.StartsWith("WM/") Then
                    If Not inWM Then
                        writer.WriteStartElement("WM")
                        inWM = True
                    End If
                    name = item.Name.Substring(3)
                ElseIf inWM Then
                    writer.WriteEndElement()
                    inWM = False
                End If
                writer.WriteStartElement("item")
                writer.WriteAttributeString("name", name)
                writer.WriteAttributeString("type", item.Type.ToString)
                writer.WriteString(item.Value.ToString)
                writer.WriteEndElement()
            Next
            If inWM Then
                writer.WriteEndElement()
            End If
            writer.WriteEndElement()
            writer.WriteEndDocument()
            writer.Close()
        End Using
    End Sub

    Private Function SaveFiles() As String
        If SaveFolder IsNot Nothing Then
            Me.fbdSave.SelectedPath = SaveFolder
        Else
            Me.fbdSave.SelectedPath = Environment.SpecialFolder.MyDocuments
        End If
        If Me.fbdSave.ShowDialog = Windows.Forms.DialogResult.OK Then
            SaveFolder = Me.fbdSave.SelectedPath
        End If
        Return SaveFolder
    End Function

    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Dim oAbout As New AboutBox1
        oAbout.ShowDialog()
    End Sub

    Private Sub LoadDVRMSFiles()
        Me.ofdDVRMS.InitialDirectory = My.Settings.RootDir
        If Me.ofdDVRMS.ShowDialog <> Windows.Forms.DialogResult.OK Then Return
        Dim sfname() As String = Me.ofdDVRMS.FileNames
        If sfname.Length = 0 Then Return
        My.Settings.RootDir = IO.Path.GetFullPath(sfname(0))
        Me.CheckedListBox1.Items.Clear()
        For Each fname As String In sfname
            Dim clbi As New DVRMSCheckedListBoxItem(fname)
            Me.CheckedListBox1.Items.Add(clbi, clbi.state)
        Next
        Me.CheckedListBox1.SetSelected(0, True)
    End Sub

    Private Sub FileMetaAttributes(ByVal fName As String)
        Using editor As New DvrmsMetadataEditor(fName)
            Dim meta As IDictionary = editor.GetAttributes
            For Each item As MetadataItem In WMTags
                If Not meta.Contains(item.Name) Then
                    Dim i As MetadataItem = item.Clone
                    meta.Add(i.Name, i)
                End If
            Next
            editor.SetAttributes(meta)
        End Using
    End Sub

    Private Sub SaveMetaAttributes(ByVal DVRMS As DVRMSCheckedListBoxItem)
        Dim item As MetadataItem
        Dim meta As IDictionary = DVRMS.meta
        If Not meta.Contains("WM/MediaIsMovie") Then
            item = New MetadataItem("WM/MediaIsMovie", False, MetadataItemType.Boolean)
            meta.Add(item.Name, item)
        Else
            item = meta.Item("WM/MediaIsMovie")
        End If
        item.Value = Me.CheckBox1.Checked
        meta.Item("WM/MediaIsMovie") = item
        If Not meta.Contains("WM/MediaCredits") Then
            item = New MetadataItem("WM/MediaCredits", "", MetadataItemType.String)
            meta.Add(item.Name, item)
        Else
            item = meta.Item("WM/MediaCredits")
        End If
        item.Value = Me.TextBox3.Text + ";" + Me.TextBox4.Text + ";;" + Me.TextBox5.Text
        meta.Item("WM/MediaCredits") = item
        If Not meta.Contains("WM/SubTitle") Then
            item = New MetadataItem("WM/SubTitle", "", MetadataItemType.String)
            meta.Add(item.Name, item)
        Else
            item = meta.Item("WM/SubTitle")
        End If
        item.Value = Me.TextBox1.Text
        meta.Item("WM/SubTitle") = item
        If Not meta.Contains("WM/SubTitleDescription") Then
            item = New MetadataItem("WM/SubTitleDescription", "", MetadataItemType.String)
            meta.Add(item.Name, item)
        Else
            item = meta.Item("WM/SubTitleDescription")
        End If
        item.Value = Me.TextBox2.Text
        meta.Item("WM/SubTitleDescription") = item
        Using editor As New DvrmsMetadataEditor(DVRMS.filename)
            Dim _meta As IDictionary = editor.GetAttributes
            editor.SetAttributes(meta)
            DVRMS.meta = meta
        End Using
        bIsDirty = False
        Me.CheckedListBox1.SetItemCheckState(Me.CheckedListBox1.SelectedIndex, CheckState.Checked)
    End Sub

    Private Sub CheckedListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles CheckedListBox1.SelectedIndexChanged
        Dim clb As CheckedListBox = CType(sender, CheckedListBox)
        If bIsDirty Then
            SaveMetaAttributes(DVRMS)
        End If
        DVRMS = clb.SelectedItem
        Dim meta As IDictionary = DVRMS.meta
        Dim item As MetadataItem
        For Each item In WMTags
            If Not meta.Contains(item.Name) Then
                Dim i As MetadataItem = item.Clone
                meta.Add(i.Name, i)
            End If
        Next
        If meta.Contains("WM/MediaIsMovie") Then
            item = meta.Item("WM/MediaIsMovie")
            Me.CheckBox1.Checked = CBool(item.Value)
        Else
            Me.CheckBox1.Checked = False
        End If
        If meta.Contains("WM/MediaCredits") Then
            item = DVRMS.meta.Item("WM/MediaCredits")
            Dim persona As String = CStr(item.Value) + ";;;;;"
            Dim credits() As String = persona.Split(";")
            Me.TextBox3.Text = credits(0)
            Me.TextBox4.Text = credits(1)
            Me.TextBox5.Text = credits(3)
        Else
            Me.TextBox3.Text = Nothing
            Me.TextBox4.Text = Nothing
            Me.TextBox5.Text = Nothing
        End If
        If meta.Contains("WM/SubTitle") Then
            item = DVRMS.meta.Item("WM/SubTitle")
            Me.TextBox1.Text = CStr(item.Value)
        Else
            Me.TextBox1.Text = Nothing
        End If
        If meta.Contains("WM/SubTitleDescription") Then
            item = meta.Item("WM/SubTitleDescription")
            Me.TextBox2.Text = CStr(item.Value)
        Else
            Me.TextBox2.Text = Nothing
        End If
        bIsDirty = False
        Using editor As New DvrmsMetadataEditor(DVRMS.filename)
            editor.SetAttributes(meta)
        End Using
    End Sub

    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles CheckBox1.CheckedChanged
        Me.CheckedListBox1.SetItemCheckState(Me.CheckedListBox1.SelectedIndex, CheckState.Unchecked)
        bIsDirty = True
    End Sub

    Private Sub TextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles TextBox5.TextChanged, TextBox4.TextChanged, TextBox3.TextChanged, TextBox2.TextChanged, _
        TextBox1.TextChanged
        Me.CheckedListBox1.SetItemCheckState(Me.CheckedListBox1.SelectedIndex, CheckState.Unchecked)
        bIsDirty = True
    End Sub

    Private Sub EditToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _
        UndoToolStripMenuItem.Click, UndoToolStripMenuItem1.Click, _
        CutToolStripMenuItem.Click, CutToolStripMenuItem1.Click, _
        CopyToolStripMenuItem.Click, CopyToolStripMenuItem1.Click, _
        PasteToolStripMenuItem.Click, PasteToolStripMenuItem1.Click, _
        SelectAllToolStripMenuItem.Click, SelectAllToolStripMenuItem1.Click
        Dim tb As TextBox
        Select Case True
            Case Me.TextBox1.Focused : tb = Me.TextBox1
            Case Me.TextBox2.Focused : tb = Me.TextBox2
            Case Me.TextBox3.Focused : tb = Me.TextBox3
            Case Me.TextBox4.Focused : tb = Me.TextBox4
            Case Me.TextBox5.Focused : tb = Me.TextBox5
            Case Else : Exit Sub
        End Select
        Select Case CType(sender, ToolStripMenuItem).Name
            Case UndoToolStripMenuItem.Name, UndoToolStripMenuItem1.Name
                If tb.CanUndo Then
                    tb.Undo()
                    tb.ClearUndo()
                End If
            Case CutToolStripMenuItem.Name, CutToolStripMenuItem1.Name : If tb.SelectionLength > 0 Then tb.Cut()
            Case CopyToolStripMenuItem.Name, CopyToolStripMenuItem1.Name : If tb.SelectionLength > 0 Then tb.Copy()
            Case PasteToolStripMenuItem.Name, PasteToolStripMenuItem1.Name
                If Clipboard.GetDataObject.GetDataPresent(DataFormats.Text) Then
                    If tb.SelectionLength > 0 Then
                    End If
                    tb.Paste()
                End If
            Case SelectAllToolStripMenuItem.Name, SelectAllToolStripMenuItem1.Name : tb.SelectAll()
        End Select
    End Sub
End Class

Public Class DVRMSCheckedListBoxItem
    Inherits CheckedListBoxItem

    Dim _meta As IDictionary = Nothing

    Public Sub New(ByVal filename As String)
        MyBase.New(filename, IO.Path.GetFileNameWithoutExtension(filename))
    End Sub

    Public Property filename() As String
        Get
            Return CStr(MyBase.item)
        End Get
        Set(ByVal value As String)
            MyBase.item = value
        End Set
    End Property

    Public Property meta() As IDictionary
        Get
            If _meta Is Nothing Then
                Using editor As New DvrmsMetadataEditor(filename)
                    _meta = editor.GetAttributes
                End Using
            End If
            Return _meta
        End Get
        Set(ByVal value As IDictionary)
            _meta = value
        End Set
    End Property

End Class

